//刷新数据
$.fn.zlzjkLoading = function(){
    $(this).append(`
            <div class="load-spinner">
                <div class="rect1"></div>
                <div class="rect2"></div>
                <div class="rect3"></div>
                <div class="rect4"></div>
                <div class="rect5"></div>
            </div>
    `);
};

$.fn.zlzjkUnloading = function(){
    $(this).find(".zlzkj_message").remove();
};

function formatTime(timestamp,fmt) {
    if(!timestamp || timestamp==='') return "";
    if(!fmt){
        fmt = "yyyy-MM-dd";
    }
        var date = new Date(timestamp);
        var o = {
            "M+" : date.getMonth() + 1, // 月份
            "d+" : date.getDate(), // 日
            "H+" : date.getHours(), // 小时
            "m+" : date.getMinutes(), // 分
            "s+" : date.getSeconds(), // 秒
            "q+" : Math.floor((date.getMonth() + 3) / 3), // 季度
            "S" : date.getMilliseconds()
            // 毫秒
        };

        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
        for ( var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
                    : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
}
//刷新数据
$.fn.zRefresh = function (url, nowPage) {
    refresh(url, nowPage);
};


function refresh(url, nowPage) {
    if (nowPage !== 0)
        $("#search-form [name=nowPage]").val(nowPage);
    $.ajax({
        type: "POST",
        url: url,
        data: $("#search-form").serialize(),
        success: function (result) {

            if (result.pageView.page.items.length === 0 && result.pageView.page.pageNum !== 1) {
                refreshTable(result.pageView.page.pageNum - 1);
                return;
            }

            $(".table-view").html($("#tableTemplate").tmpl(result));

            $("#page-div").html(pageGenerator(result.pageView));

            //添加点击事件
            initOperation();
        }
    });

}


$.fn.onZCreate = function (url, formValidate) {
    $(this).off("click").on("click", function () {
        $.post(url, {}, function (result, textStatus, xhr) {
            $("#commonModal .modal-content").html($("#objTemplate").tmpl(result));
            formValidate();
        });
        return false;
    });
    return $(this);
};

$.fn.onZEdit = function (url, formValidate) {
    $(this).off("click").on("click", function () {
        $.post(url, {id: $(this).closest("tr").data("id")}, function (result, textStatus, xhr) {
            $("#commonModal .modal-content").html($("#objTemplate").tmpl(result));
            formValidate();
        });
        return false;
    });
    return $(this);
};

$.fn.onZDelete = function (url) {
    $(this).off("click").on("click", function () {
        let id = $(this).closest("tr").data("id");
        zConfirm("确认要删除'<font color='#f00'>" + $(this).closest("tr").data("name") + "</font>'吗？", url, {id: id}, function (data) {
                if (data > 0) {
                    refreshTable(0);
                    noty_success('删除成功');
                } else {
                    noty_fail('删除失败');
                }
            }
        );
        return false;
    });
    return $(this);
};

$.fn.onZDisable = function (url) {

    $(this).off("click").on("click", function () {
        let id = $(this).closest("tr").data("id");

        zConfirm("确认要禁用'<font color='#f00'>" + $(this).closest("tr").data("name") + "</font>'吗？", url, {id: id}, function (data) {
                if (data > 0) {
                    refreshTable(0);
                    noty_success('禁用成功');
                } else {
                    noty_fail('操作失败');
                }
            }
        );
        return false;
    });
    return $(this);
};

$.fn.onZEnable = function (url) {

    $(this).off("click").on("click", function () {
        let id = $(this).closest("tr").data("id");

        zConfirm("确认要启用'<font color='#f00'>" + $(this).closest("tr").data("name") + "</font>'吗？", url, {id: id}, function (data) {
                if (data > 0) {
                    refreshTable(0);
                    noty_success('启用成功');
                } else {
                    noty_fail('操作失败');
                }
            }
        );
        return false;
    });
    return $(this);
};

$.fn.onZBatchDelete = function (url) {

    $(this).off("click").on("click", function () {
        let checkbox = $("input[type=checkbox]:checked");
        if (checkbox.length === 0) return;
        let content = "";
        for (let i = 0; i < checkbox.length; i++) {
            content += "'<font color='#3671be'>" + checkbox.eq(i).closest("tr").data("name") + "</font>'&nbsp;";
        }

        zConfirm("确认要删除" + content + ",这<font color='#f00'>" + checkbox.length + "</font>条数据吗？",
            url, $(".ids-form").serialize(), function (data) {
                if (data > 0) {
                    refreshTable(0);
                    noty_success('删除成功');
                } else {
                    noty_fail('删除失败');
                }
            }
        );
        return false;
    });
    return $(this);
};


function pageGenerator(page) {
    if (page.page.totalPage !== 1) {

        let headPage = ``;
        if (page.page.pageNum === 1) {
            headPage = `<li class="disabled"><a href="javascript:void(0);">‹</a></li>`;
        } else {
            headPage = `<li><a href="javascript:refreshTable(${page.page.pageNum - 1 || 1})"><span>‹</span></a>`;
        }

        let middlePage = ``;
        $.each(page.showPages, function (i, v) {
            if (v === page.page.pageNum) {
                middlePage += `<li class="active"><a href="javascript:void(0);">${v}</a></li>`;
            } else if (v === 0) {
                middlePage += `<li><a>...</a></li>`;
            } else {
                middlePage += `<li><a href="javascript:refreshTable(${v || 0})"><span>${v || 0}</span></a></li>`;
            }

        });

        let tailPage = ``;

        if (page.page.pageNum === page.page.totalPage) {
            tailPage = `<li class="disabled"><a href="javascript:void(0);">›</a></li>`;
        } else {
            tailPage = `<li><a href="javascript:void(0);" onclick="refreshTable(${page.page.pageNum + 1 || 1})"><span>›</span></a>`;
        }

        let pageHtml =
            `<nav class="zlzkj_pagination">
                <ul class="pagination">
                    ${headPage}
                    ${middlePage}
                    ${tailPage}
                </ul>
            </nav>`;
        return pageHtml;
    }else{
        return '';
    }
}

function zConfirm(str, url, data, success, cancel) {
    $.confirm({
        title: '系统提示',
        content: str,
        buttons: {
            ok: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.post(url, data, function (data, textStatus, xhr) {
                        success(data);
                    });
                }
            },
            cancel: {
                text: '取消',
                btnClass: 'btn-primary',
                action: function () {
                    if (cancel) {
                        cancel();
                    }
                    // button action.
                }
            },
        }
    });
}


$.fn.onZSelect2 = function (url,info,itemUrl,attr,all) {
    if(!attr){
        attr = 'name';
    }
    let element = $(this);
    $(this).select2({
        ajax: {
            type: 'GET',
            url: url,
            async: false,
            dataType: 'json',
            delay: 250,
            data: function (params) {
                //return $("#cur-form").serialize();
                return {
                    q: params.term, // search term 请求参数
                };
            },
            processResults: function (data) {
                var arr = [];
                if(all){
                    arr.push({id: -1, text: '全部'});
                }
                var result = data.result;
                for (var i = 0; i < result.length; i++) {
                    arr.push({id: result[i].id, text: result[i][attr]});
                }
                return {
                    results: arr
                };
            },
            cache: true
        },
        placeholder: info,//默认文字提示
        language: "zh-CN",
        allowClear: true,//允许清空
        minimumInputLength: 0
    });

    if($(this).data("value") !== undefined && $(this).data("value") !== ''){
        //noty_success($(this).data("value"));
        $.post(itemUrl, {id:$(this).data("value")}, function (result, textStatus, xhr) {
            $(element).append(new Option(result.obj.name, result.obj.id, true, true));
        });
    }

    $(this).on("select2:select", function () {
        $(this).blur();
    });

};


$.fn.onZVideo = function () {

    $(this).off("click").on("click", function () {
        var url = $(this).data("url");

        $("#commonVideoModal").modal('show');

        videojs("my-video").ready(function () {
            var myPlayer = this;
            myPlayer.src(url);
            //myPlayer.load();//使video重新加载
            myPlayer.play();//播放视频
        });
    });
    return $(this);
};

/*$(".select_material").on("select2:select", function () {
    var id = $(".select_material").select2("data")[0].id;
    $.ajax({
        type: "GET",
        url: "${ctx}/baseinfo/material/getMaterial.action",
        data: {id: id},
        success: function (result) {
            result.index = index++;
            $("#materialTemplate").tmpl(result).appendTo($(".table tbody"));
            $(".table tbody tr:last input[name$=materialAmount]").rules("add", {
                number: true,
                required: true,
                maxlength: 10,
                min: 0
            });

            $(".nodata").hide();
            $(".select_material").val("添加原材料").trigger("change");
        }
    });
});*/

/*$(function () {

    zConfirm("确认要删除吗？", "http://localhost:8080/smartfire/user/to_edit", {id: 17, 2: 2}, function (data) {
            if (data > 0) {
                refreshTable(0);
                noty_success('删除成功');
            } else {
                noty_fail('删除失败');
            }
        }
    );

    zConfirm("确认要删除吗？", "http://localhost:8080/smartfire/user/to_edit", {id: 17, 2: 2}, function (data) {
            if (data > 0) {
                refreshTable(0);
                noty_success('删除成功');
            } else {
                noty_fail('删除失败');
            }
        }, function () {
            noty_fail('cancel!');
        }
    );
});*/


/*
var hang = function(){
    alert(1);
}
$.fn.initZ = function(url,hang) {
    if(hang){
        hang();
    }

}

$("body").initZ(1,hang);*/
